package so.shanku.essential.activity;

import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.LeftMenuCheckboxAdapter;
import so.shanku.essential.adapter.MenuAdapter;
import so.shanku.essential.adapter.RelationProductAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.view.NoTouchLinearLayout;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Jaelyn on 16/3/30.
 * 商品大分类,品牌点击详情
 */
public class ProductCategoryRelationActivity extends BaseUIActivity {
    @ViewInject(id = R.id.sort_tv)
    private TextView sort_tv;
    @ViewInject(id = R.id.sort_tv_layout, click = "sort_tv_click")
    private LinearLayout sort_tv_layout;
//    @ViewInject(id = R.id.discount_cb)
//    private CheckBox discount_cb;
//    @ViewInject(id = R.id.self_product_cb)
//    private CheckBox self_product_cb;
    @ViewInject(id = R.id.discount_cb)
    private LinearLayout discount_cb;
    @ViewInject(id = R.id.self_product_cb)
    private LinearLayout self_product_cb;

    @ViewInject(id = R.id.ptr_gv)
    private PullToRefreshGridView ptr_gv;

    /**
     * 排序
     */
    @ViewInject(id = R.id.no_touch_layout)
    private NoTouchLinearLayout no_touch_layout;

    /**
     * 侧滑抽屉
     */
    @ViewInject(id = R.id.drawer_layout)
    private DrawerLayout drawer_layout;

    @ViewInject(id = R.id.left_drawer)
    private LinearLayout left_drawer;
    /**
     * 分类
     */
    @ViewInject(id = R.id.classfy_layout)
    private LinearLayout classfy_layout;
    @ViewInject(id = R.id.classfy_lv)
    private ListView classfy_lv;


    /**
     * 品牌
     */
    @ViewInject(id = R.id.brand_layout)
    private LinearLayout brand_layout;
    @ViewInject(id = R.id.brand_lv)
    private ListView brand_lv;

    @ViewInject(id = R.id.btn_cancel, click = "btn_cancel_click")
    private Button btn_cancel;

    @ViewInject(id = R.id.btn_confirm, click = "btn_confirm_click")
    private Button btn_confirm;

    /**
     * 对的品牌 侧滑需要
     */
    private ArrayList<JsonMap<String, Object>> brandsList = new ArrayList<JsonMap<String, Object>>();
    /**
     * 侧边栏选中的数据
     */
    private ArrayList<JsonMap<String, Object>> selectBrandsList = new ArrayList<JsonMap<String, Object>>();

    /**
     * 二级分类
     */
    private ArrayList<JsonMap<String, Object>> classfyList = new ArrayList<JsonMap<String, Object>>();
    /**
     * 侧边栏选中的数据
     */
    private ArrayList<JsonMap<String, Object>> selectClassfyList = new ArrayList<JsonMap<String, Object>>();
    /**
     * 商品
     */
    private ArrayList<JsonMap<String, Object>> dataList = new ArrayList<JsonMap<String, Object>>();
    private RelationProductAdapter relationProductAdapter;

    /**
     * 排序
     */
    private ArrayList<JsonMap<String, Object>> sortList = new ArrayList<JsonMap<String, Object>>();

    /**
     * 商品大分类的id
     */
    private String categoryId;
    /**
     * 排序方式
     */
    private String sortId = "2";
    /**
     * 界面跳转来源
     */
    private int flag = 1;
    private int nPage = 0;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.productcategory_relationproduct_layout);
        setShowLeftMenu(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sortStatus(false);
                if (drawer_layout.isDrawerVisible(left_drawer)) {
                    drawer_layout.closeDrawer(left_drawer);
                } else {
                    drawer_layout.openDrawer(left_drawer);
                }
            }
        });
        categoryId = getIntent().getStringExtra(Constant.ID);
        setCenter_title(getIntent().getStringExtra(Constant.NAME));
        flag = getIntent().getIntExtra(ExtraKeys.Key_Msg1, 1);
        setBtn_menu(R.drawable.search_white, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToSearchProduct();
                sortStatus(false);

            }
        }, R.drawable.shopcart_white, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToShopCart();
                sortStatus(false);
            }
        });

        ptr_gv.setOnRefreshListener(list_loadMoreListener);
        //loadingToast.show();
        //getServiceData(true);
        ptr_gv.setOnItemClickListener(onItemClickListener);
        self_product_cb.setOnClickListener(checkedChangeListener);
        discount_cb.setOnClickListener(checkedChangeListener);
        relationProductAdapter = new RelationProductAdapter(mContext);
        relationProductAdapter.setShowDiscri(true);
        ptr_gv.setAdapter(relationProductAdapter);

        getClassfyDataById();
        getServiceData(true);

        initSortView();
    }

    /**
     * 初始化排序view和数据
     */
    private void initSortView() {
        JsonMap<String, Object> sortJson2 = new JsonMap<String, Object>();
        sortJson2.put("categoryName", getString(R.string.multiple));
        sortJson2.put("sortId", 2);
        sortList.add(sortJson2);


        JsonMap<String, Object> sortJson1 = new JsonMap<String, Object>();
        sortJson1.put("categoryName", getString(R.string.price_f_high_to_low));
        sortJson1.put("sortId", 1);
        sortList.add(sortJson1);

        JsonMap<String, Object> sortJson0 = new JsonMap<String, Object>();
        sortJson0.put("categoryName", getString(R.string.price_f_low_to_high));
        sortJson0.put("sortId", 0);
        sortList.add(sortJson0);

        ListView listView = new ListView(mContext);
        listView.setDivider(mContext.getResources().getDrawable(R.drawable.hor_line));
        int pad = getResources().getDimensionPixelSize(R.dimen.common_margin);
        listView.setPadding(pad, 0, pad, 0);
        listView.setBackgroundResource(R.drawable.cus_grey_border_frame);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                sortStatus(false);
                sort_tv.setText(sortList.get(position).getStringNoNull("categoryName"));
                String tempSortId = sortList.get(position).getString("sortId");
                if (!tempSortId.endsWith(sortId)) {
                    getServiceData(true);
                }
            }
        });
        MenuAdapter menuAdapter = new MenuAdapter(mContext, sortList);
        listView.setAdapter(menuAdapter);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(MyApplication.getInstance().getScreenWidth() / 3, ViewGroup.LayoutParams.WRAP_CONTENT);
        no_touch_layout.addView(listView, params);
        //no_touch_layout.setTouchOutSideCancel(true);
    }


    /**
     * 获取左侧的侧滑数据
     */
    private void getClassfyDataById() {
        HashMap hashMap = new HashMap();
        hashMap.put("categoryId", categoryId);

        GetDataQueue getDataQueue = new GetDataQueue();
        if (flag == 1) {
            getDataQueue.setActionName(GetDataConfing.GetAction_GetClassfyDataByProductCategoryId);
        } else if (flag == 2) {
            getDataQueue.setActionName(GetDataConfing.GetAction_GetClassfyDataByBrandId);
        }
        getDataQueue.setWhat(GetDataConfing.What_GetClassfyDataByProductCategoryId);
        getDataQueue.setParamsNoJson(hashMap);

        getDataQueue.setCallBack(callBack);
        getDataUtil.getData(getDataQueue);
    }

    /**
     * 排序点击
     *
     * @param view
     */
    public void sort_tv_click(View view) {
        if (no_touch_layout.getVisibility() == View.VISIBLE) {
            sortStatus(false);
        } else {
            sortStatus(true);
        }
    }

    /**
     * 排序状态显示
     *
     * @param status 0:不显示,1:显示
     */
    private void sortStatus(boolean status) {
        if (status) {
            no_touch_layout.setVisibility(View.VISIBLE);
            sort_tv.setSelected(true);

        } else {
            no_touch_layout.setVisibility(View.GONE);
            sort_tv.setSelected(false);
        }
    }

    /**
     * checkbox 状态改变的监听
     */
    View.OnClickListener checkedChangeListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boolean bool=view.isSelected();
            view.setSelected(!bool);
            getServiceData(true);
            sortStatus(false);
        }
    };

    /**
     * 商品 item的点击
     */
    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String productId = dataList.get(position).getStringNoNull("productId");
            seeProductDetail(productId);
        }
    };

    /**
     * Gridview
     */
    PullToRefreshBase.OnRefreshListener2 list_loadMoreListener = new PullToRefreshBase.OnRefreshListener2<GridView>() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
            getServiceData(true);
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
            getServiceData(false);
        }
    };

    /**
     * 获取网络数据
     * private int nPage = 0;
     * /**
     *
     * @param chearAllData
     */
    private void getServiceData(boolean chearAllData) {
        if (chearAllData) {
            nPage = 0;
            ptr_gv.setMode(PullToRefreshBase.Mode.BOTH);
        }
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("categoryId", categoryId);

        params.put("sortId", "" + sortId);
        params.put("isDiscount", discount_cb.isSelected() ? 1 : 0);
        params.put("selfOwened", self_product_cb.isSelected() ? 1 : 0);
        params.put("searchKey", "");
        params.put("productClassfyList", selectClassfyList);
        params.put("brandList", selectBrandsList);
        params.put("nPage", nPage + 1);

        GetDataQueue queue = new GetDataQueue();
        if (flag == 1) {
            queue.setActionName(GetDataConfing.GetAction_SelectSearchProductList);
        } else if (flag == 2) {
            queue.setActionName(GetDataConfing.GetAction_SelectBrandProductList);
        }
        queue.setWhat(GetDataConfing.what_SelectSearchProductList);
        queue.setCallBack(callBack);

        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }

    /**
     * 设置适配器数据
     *
     * @param data
     */
    private void setAdapterData(ArrayList<JsonMap<String, Object>> data) {
        if (data.size() == 0) {
            ptr_gv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            ptr_gv.setMode(PullToRefreshBase.Mode.BOTH);
        }
        if (nPage == 0) {
            this.dataList = data;
            relationProductAdapter = new RelationProductAdapter(this);
            relationProductAdapter.setDatas(data);
            relationProductAdapter.setShowDiscri(true);
            ptr_gv.setAdapter(relationProductAdapter);
        } else {
            this.dataList.addAll(data);
            relationProductAdapter.notifyDataSetChanged();
        }
        nPage++;
    }


    /**
     * 获取服务器数据的返回信息
     */
    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.what_SelectSearchProductList || entity.getWhat() == GetDataConfing.What_SelectBrandProductList) {
                        ArrayList<JsonMap<String, Object>> data = (ArrayList<JsonMap<String, Object>>) JsonParseHelper.getJsonMap_List_JsonMap(
                                entity.getInfo(), JsonKeys.Key_Info);
                        setAdapterData(data);
                    } else if (entity.what == GetDataConfing.What_GetClassfyDataByProductCategoryId || entity.getWhat() == GetDataConfing.What_GetClassfyDataByBrandId) {
                        JsonMap jsonMap = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        brandsList = (ArrayList<JsonMap<String, Object>>) jsonMap.getList_JsonMap("brandList");
                        classfyList = (ArrayList<JsonMap<String, Object>>) jsonMap.getList_JsonMap("productClassfyList");
                        showLeftData();
                    }
                }
            } else {
                ShowGetDataError.showNetError(mContext);

            }
            loadingToast.dismiss();
            ptr_gv.onRefreshComplete();
        }
    };


    /**
     * 侧滑数据解析
     */
    private LeftMenuCheckboxAdapter leftBrandMenuCheckboxAdapter;
    private LeftMenuCheckboxAdapter leftClassfyMenuCheckboxAdapter;

    private void showLeftData() {
        if (brandsList.size() == 0) {
            brand_layout.setVisibility(View.GONE);
        } else {
            leftBrandMenuCheckboxAdapter = new LeftMenuCheckboxAdapter(mContext, brandsList);
            brand_lv.setAdapter(leftBrandMenuCheckboxAdapter);
        }

        if (classfyList.size() == 0) {
            classfy_layout.setVisibility(View.GONE);
        } else {
            leftClassfyMenuCheckboxAdapter = new LeftMenuCheckboxAdapter(mContext, classfyList);
            classfy_lv.setAdapter(leftClassfyMenuCheckboxAdapter);
        }
    }

    /**
     * 确定按钮点击
     *
     * @param view
     */
    public void btn_confirm_click(View view) {
        selectBrandsList.clear();
        selectClassfyList.clear();
        drawer_layout.closeDrawer(left_drawer);
        if (!brandsList.isEmpty()) {
            brandsList = (ArrayList<JsonMap<String, Object>>) leftBrandMenuCheckboxAdapter.getDatas();
            for (int i = 0; i < brandsList.size(); i++) {
                JsonMap jsonMap = brandsList.get(i);
                if (jsonMap.getBoolean("isChecked")) {
                    selectBrandsList.add(jsonMap);
                }
            }
        }
        if (!classfyList.isEmpty()) {
            classfyList = (ArrayList<JsonMap<String, Object>>) leftClassfyMenuCheckboxAdapter.getDatas();
            for (int i = 0; i < classfyList.size(); i++) {
                JsonMap jsonMap = classfyList.get(i);
                if (jsonMap.getBoolean("isChecked")) {
                    selectClassfyList.add(jsonMap);
                }
            }

        }
        getServiceData(true);
    }

    /**
     * 取消按钮点击
     *
     * @param view
     */
    public void btn_cancel_click(View view) {
        drawer_layout.closeDrawer(left_drawer);
    }

    @Override
    public void onBackPressed() {
        //退出activity前关闭菜单
        if (no_touch_layout.getVisibility() == View.VISIBLE) {
            no_touch_layout.setVisibility(View.GONE);
        } else if (drawer_layout.isDrawerOpen(left_drawer)){
            drawer_layout.closeDrawer(left_drawer);
        } else {
            super.onBackPressed();
        }
    }
}